{% extends "admin/admin_base.html" %}

{% block title %}用户管理{% endblock %}
{% block breadcrumb %}用户管理{% endblock %}
{% block content %}
<style>
    /* 统计卡片 */
    .stats-container {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1.5rem;
        margin-bottom: 1.5rem;
    }

    .stat-card {
        background-color: white;
        border-radius: 0.75rem;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        padding: 1.5rem;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }

    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    }

    .stat-card-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 1rem;
    }

    .stat-card-title {
        color: #86909C;
        font-size: 0.875rem;
        font-weight: 500;
    }

    .stat-card-icon {
        width: 40px;
        height: 40px;
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.25rem;
    }

    .stat-card-icon.primary {
        background-color: rgba(22, 93, 255, 0.1);
        color: var(--primary-color);
    }

    .stat-card-icon.success {
        background-color: rgba(0, 180, 42, 0.1);
        color: var(--success-color);
    }

    .stat-card-icon.warning {
        background-color: rgba(255, 125, 0, 0.1);
        color: var(--warning-color);
    }

    .stat-card-icon.danger {
        background-color: rgba(245, 63, 63, 0.1);
        color: var(--danger-color);
    }

    .stat-card-value {
        font-size: 1.75rem;
        font-weight: 600;
        margin-bottom: 0.5rem;
    }

    .stat-card-trend {
        display: flex;
        align-items: center;
        gap: 0.25rem;
        font-size: 0.875rem;
    }

    .trend-up {
        color: var(--success-color);
    }

    .trend-down {
        color: var(--danger-color);
    }


    .badge {
        padding: 0.25rem 0.5rem;
        border-radius: 999px;
        font-size: 0.75rem;
        font-weight: 500;
    }

    .badge-success {
        background-color: rgba(0, 180, 42, 0.1);
        color: var(--success-color);
    }

    .badge-danger {
        background-color: rgba(245, 63, 63, 0.1);
        color: var(--danger-color);
    }

    .badge-warning {
        background-color: rgba(255, 125, 0, 0.1);
        color: var(--warning-color);
    }

    .badge-primary {
        background-color: rgba(22, 93, 255, 0.1);
        color: var(--primary-color);
    }

    /* 金牌用户（月度会员） */
    .badge-month {
        background-color: #FFF9C4; /* 浅金背景（接近鎏金质感） */
        color: #D4AF37; /* 金属金色文字 */
        border: 1px solid #FFECB3; /* 浅边框增强层次感 */
    }

    /* 铂金用户（季度会员） */
    .badge-season {
        background-color: #E3F2FD; /* 淡蓝背景（类似铂金冷冽感） */
        color: #1976D2; /* 钴蓝色文字 */
        border: 1px solid #BBDEFB; /* 更浅的蓝边框 */
    }

    /* 至尊用户（年度/管理员） */
    .badge-year,
    .badge-admin {
        background: linear-gradient(135deg, #7B1FA2 0%, #4A148C 100%); /* 紫红渐变（尊贵感） */
        color: #FFFFFF; /* 白色文字高对比 */
        box-shadow: 0 2px 4px rgba(123, 31, 162, 0.15); /* 轻微投影提升立体感 */
    }

    /* 普通用户 */
    .badge-free {
        background-color: #F5F5F5; /* 浅灰背景（中性百搭） */
        color: #616161; /* 深灰文字 */
        border: 1px solid #EEEEEE; /* 极浅灰边框 */
    }

    .action-btn {
        background: none;
        border: none;
        color: #86909C;
        cursor: pointer;
        padding: 0.25rem;
        margin: 0 0.125rem;
        transition: color 0.2s ease;
    }


</style>
<!--<h2 class="mb-4">用户管理</h2>-->
<!-- 统计卡片 -->
<div class="stats-container">
    <div class="stat-card">
        <div class="stat-card-header">
            <div class="stat-card-title">总用户数</div>
            <div class="stat-card-icon primary">
                <i class="fas fa-users"></i>
            </div>
        </div>
        <div class="stat-card-value">{{ stats.total_users }}</div>
        <div class="stat-card-trend trend-{{ 'up' if stats.total_users_growth  > 0 else 'down' }}">
            <i class="fas fa-arrow-{{ 'up' if stats.total_users_growth  > 0 else 'down' }}"></i>
            <span>较上月{{ '增长' if stats.total_users_growth  > 0 else '下降' }}{{ stats.total_users_growth }}% </span>
        </div>
    </div>

    <div class="stat-card">
        <div class="stat-card-header">
            <div class="stat-card-title">活跃用户</div>
            <div class="stat-card-icon success">
                <i class="fas fa-user-check"></i>
            </div>
        </div>
        <div class="stat-card-value">{{ stats.active_count }}</div>
        <div class="stat-card-trend trend-{{ 'up' if stats.week_active_growth > 0 else 'down' }}">
            <i class="fas fa-arrow-{{ 'up' if stats.week_active_growth > 0 else 'down' }}"></i>
            <span>较上周{{ '增长' if stats.week_active_growth > 0 else '下降' }} {{ stats.week_active_growth }}% </span>
        </div>
    </div>

    <div class="stat-card">
        <div class="stat-card-header">
            <div class="stat-card-title">会员用户</div>
            <div class="stat-card-icon warning">
                <i class="fas fa-user-plus"></i>
            </div>
        </div>

        <div class="stat-card-value">{{ stats.vip_count }}</div>
        <div class="stat-card-trend trend-{{ 'up' if stats.week_vip_growth > 0 else 'down' }}">
            <i class="fas fa-arrow-{{ 'up' if stats.week_vip_growth > 0 else 'down' }}"></i>
            <span>较上周{{ '增长' if stats.week_vip_growth > 0 else '下降' }} {{ stats.week_vip_growth}}% </span>
        </div>
    </div>

    <div class="stat-card">
        <div class="stat-card-header">
            <div class="stat-card-title">今日新增</div>
            <div class="stat-card-icon danger">
                <i class="fas fa-user-plus"></i>
            </div>
        </div>
        <div class="stat-card-value">{{ stats.today_new_users }}</div>
        <div class="stat-card-trend trend-{{ 'up' if stats.today_user_growth  > 0 else 'down' }}">
            <i class="fas fa-arrow-{{ 'up' if stats.today_user_growth  > 0 else 'down' }}"></i>
            <span>较昨日{{ '增长' if stats.today_user_growth  > 0 else '下降' }} {{ stats.today_user_growth }}% </span>
        </div>
    </div>
</div>

<!-- 用户表格 -->
<div class="data-table mb-4">
    <div class="table-header">
        <div class="table-title">用户列表</div>
        <div class="table-actions">
            <form id="searchForm" class="input-group" style="width: 300px;" method="get">
                <input type="text" name="search" class="form-control" placeholder="搜索用户名、ID..."
                       value="{{ search or '' }}">
                <button class="btn btn-primary" type="submit">
                    <i class="fas fa-search"></i>
                </button>
            </form>
            <button class="btn btn-primary" id="addUserBtn">
                <i class="fas fa-plus"></i> 添加用户
            </button>
        </div>
    </div>
    <div class="table-responsive">
        <table>
            <thead>
            <tr>
                <th>用户ID</th>
                <th>用户名</th>
                <th>用户类型</th>
                <th>状态</th>
                <th>今日调用</th>
                <th>接口ID</th>
                <th>接口密钥</th>
                <th>注册时间</th>
                <th>会员到期时间</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% for user in users %}
            <tr>
                <td>{{ user.user_id }}</td>
                <td>{{ user.username }}</td>
                <td>
                    {% if user.user_type.value == 'month' %}
                    <span class="badge badge-month">金牌用户</span>
                    {% elif user.user_type.value == 'season' %}
                    <span class="badge badge-season">铂金用户</span>
                    {% elif user.user_type.value == 'year' %}
                    <span class="badge badge-year">至尊用户</span>
                    {% elif user.user_type.value == 'admin' %}
                    <span class="badge badge-admin">至尊用户</span>
                    {% else %}
                    <span class="badge badge-free">普通用户</span>
                    {% endif %}
                </td>
                <td>
                    {% if user.status == 1 %}
                    <span class="badge badge-success">正常</span>
                    {% else %}
                    <span class="badge badge-danger">禁用</span>
                    {% endif %}
                </td>
                <td>{{ user.today_call.call_count or '-' }}</td>
                <td>{{ user.client_id }}</td>
                <td>{{ user.client_secret or "--"}}</td>
                <td>{{ user.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
                <td>{{ user.vip_expire.strftime('%Y-%m-%d %H:%M') if user.vip_expire is not none else '--' }}</td>
                <td>
                    <button class="action-btn btn btn-sm btn-info" title="查看详情" data-id="{{ user.user_id }}"
                            data-action="view">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="action-btn btn btn-sm btn-warning" title="编辑" data-id="{{ user.user_id }}"
                            data-action="edit">
                        <i class="fas fa-edit"></i>
                    </button>
                    {% if user.status == 1 %}
                    <button class="action-btn btn btn-sm btn-danger" title="禁用" data-id="{{ user.user_id }}"
                            data-action="disable">
                        <i class="fas fa-ban"></i>
                    </button>
                    {% else %}
                    <button class="action-btn btn btn-sm btn-success" title="启用" data-id="{{ user.user_id }}"
                            data-action="disable">
                        <i class="fas fa-check"></i>
                    </button>
                    {% endif %}
                </td>
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
    <div class="pagination-container d-flex justify-content-between align-items-center mt-3">
        <div class="pagination-info">显示 {{ users|length }} 条，共 {{ total_users }} 条</div>
        <div class="pagination">
        <!-- 上一页 -->
        <a href="?page={{ page-1 if page > 1 else 1 }}{% if search %}&search={{ search }}{% endif %}"
           class="btn {% if page == 1 %}btn-outline-secondary disabled{% else %} btn-outline-primary{% endif %}">
            <i class="fas fa-chevron-left"></i>
        </a>

        <!-- 分页按钮（修复 max/min 问题） -->
        {% if total_pages > 0 %}
            {% set start_page = (page - 2) if (page - 2) >= 1 else 1 %}
            {% set end_page = (page + 2) if (page + 2) <= total_pages else total_pages %}
            {% for p in range(start_page, end_page + 1) %}
                <a href="?page={{ p }}{% if search %}&search={{ search }}{% endif %}"
                   class="btn btn-outline-primary {% if p == page %}active{% endif %}">{{ p }}</a>
            {% endfor %}
        {% endif %}

        <!-- 下一页 -->
        <a href="?page={{ page+1 if page < total_pages else total_pages }}{% if search %}&search={{ search }}{% endif %}"
           class="btn {% if page == total_pages %}btn-outline-secondary disabled{% else %} btn-outline-primary{% endif %}">
            <i class="fas fa-chevron-right"></i>
        </a>
    </div>
    </div>


</div>

<!-- 添加 / 查看 / 编辑用户模态框 -->
<div class="form-modal" id="addUserModal">
    <div class="modal-content">
        <form id="addUserForm">
            <input type="hidden" name="user_id" value="">
            <div class="modal-header">
                <h3 class="modal-title">添加新用户</h3>
                <button class="modal-close" id="closeUserModal" type="button">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">用户名</label>
                    <input type="text" name="username" class="form-control" required placeholder="请输入用户名">
                </div>
                <div class="form-group">
                    <label class="form-label">密码</label>
                    <input type="password" name="password" class="form-control" placeholder="请输入密码">
                </div>
                <div class="form-group">
                    <label class="form-label">用户类型</label>
                    <select name="user_type" class="form-control" required>
                        <option value="free">free - 免费用户</option>
                        <option value="month">month - 月会员</option>
                        <option value="season">season - 季会员</option>
                        <option value="year">year - 年会员</option>
                        <option value="admin">admin - 管理员</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">状态</label>
                    <select name="status" class="form-control" required>
                        <option value="1">1 - 正常</option>
                        <option value="0">0 - 禁用</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">会员到期时间</label>
                    <input type="date" name="vip_expire" class="form-control">
                    <small class="text-muted">免费用户和管理员可不填</small>
                </div>
                <div class="form-group">
                    <label class="form-label">激活方式</label>
                    <select name="activation_method" class="form-control">
                        <option value="">请选择</option>
                        <option value="wechat">wechat - 微信支付</option>
                        <option value="alipay">alipay - 支付宝</option>
                        <option value="kami">kami - 卡密激活</option>
                        <option value="manual">manual - 手动激活</option>
                        <option value="other">other - 其他方式</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline" id="cancelAddUser" type="button">取消</button>
                <button class="btn btn-primary" type="submit">创建用户</button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener("DOMContentLoaded", () => {
        const addUserBtn = document.getElementById("addUserBtn");
        const addUserModal = document.getElementById("addUserModal");
        const closeUserModal = document.getElementById("closeUserModal");
        const cancelAddUser = document.getElementById("cancelAddUser");
        const submitUserBtn = addUserModal.querySelector("button[type='submit']");
        const userForm = document.getElementById("addUserForm");

        // 打开添加用户模态框
        addUserBtn.addEventListener("click", () => {
            resetForm();
            submitUserBtn.textContent = "创建用户";
            submitUserBtn.dataset.action = "add";
            addUserModal.classList.add("show");
        });

        closeUserModal.addEventListener("click", () => addUserModal.classList.remove("show"));
        cancelAddUser.addEventListener("click", () => addUserModal.classList.remove("show"));

        // 点击模态框外部关闭
        window.addEventListener("click", (e) => {
            if (e.target.classList.contains("form-modal")) {
                e.target.classList.remove("show");
            }
        });

        // 表格操作按钮
        document.querySelectorAll(".action-btn").forEach(btn => {
            btn.addEventListener("click", async () => {
                const userId = btn.dataset.id;
                const action = btn.dataset.action;
                const titleEl = addUserModal.querySelector(".modal-title");

                if (action === "view" || action === "edit") {
                    const res = await fetch(`/admin/users/action?action=${action}`, {
                        method: "POST",
                        headers: {"Content-Type": "application/json"},
                        body: JSON.stringify({user_id: userId, action: 'get'})
                    });
                    const data = await res.json();
                    console.log(data);  // 看看这里是不是有 user
                    if (!data.success) return alert(data.msg);
                    fillForm(data.user);
                    titleEl.textContent = action === "view" ? "查看用户" : "编辑用户";
                    submitUserBtn.textContent = action === "view" ? "关闭" : "保存修改";
                    submitUserBtn.dataset.action = action;
                    submitUserBtn.dataset.userId = userId;

                    userForm.querySelectorAll("input, select").forEach(el => el.disabled = action === "view");

                    addUserModal.classList.add("show");
                }

                if (action === "disable") {
                    if (!confirm("确定要修改用户状态吗？")) return;
                    const res = await fetch(`/admin/users/action?action=disable`, {
                        method: "POST",
                        headers: {"Content-Type": "application/json"},
                        body: JSON.stringify({user_id: userId})
                    });
                    const data = await res.json();
                    // alert(data.msg);
                    message('success', data.msg);
                    location.reload();
                    // window.location.href = "/admin/users";
                }
            });
        });

        // 保存/提交按钮点击
        submitUserBtn.addEventListener("click", async (e) => {
            e.preventDefault();
            const action = submitUserBtn.dataset.action;
            const userId = submitUserBtn.dataset.userId;

            if (action === "view") {
                addUserModal.classList.remove("show");
                return;
            }

            // 收集表单字段
            const payload = {
                user_id: userId,
                username: userForm.username.value,
                password: userForm.password.value,
                user_type: userForm.user_type.value,
                status: userForm.status.value,
                vip_expire: userForm.vip_expire.value,
                activation_method: userForm.activation_method.value
            };

            const res = await fetch(`/admin/users/action?action=${action}`, {
                method: "POST",
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify(payload)
            });

            const data = await res.json();
            alert(data.msg);
            if (data.success) {
                addUserModal.classList.remove("show");
                location.reload();  // 刷新表格
            }
        });


        function resetForm() {
            userForm.reset();
            userForm.querySelectorAll("input, select").forEach(el => el.disabled = false);
            submitUserBtn.dataset.userId = "";
        }

        function fillForm(user) {
            userForm.username.value = user.username || "";
            userForm.password.value = ""; // 编辑用户时密码不填
            userForm.user_type.value = user.user_type || "";
            userForm.status.value = String(user.status || "1"); // select value 必须是字符串
            userForm.vip_expire.value = user.vip_expire || "";
            userForm.activation_method.value = user.activation_method || "";
        }


    });
</script>
{% endblock %}
